package com.rgs.se.concurrent.countDownLatch;

import java.util.concurrent.*;

/**
 * @author Ren Gaoshuai
 * @ClassName RealityTest
 * @Description CountDownLatch 真实使用
 * @date 2021-10-27 15:49
 **/
public class RealityTest {

    /**
     * 业务场景，需要将10填内的数据进行获取，打包压缩成zip，
     * 使用多线程获取比较快，但是要控制打印线程在获取数据线程执行完成后在执行，否则会出现数据缺失
     */

    private static CountDownLatch countDownLatch = new CountDownLatch(10);

    private static ExecutorService executorService = new ThreadPoolExecutor(5,
            20,
            10,
            TimeUnit.MICROSECONDS,
            new LinkedBlockingQueue<Runnable>(10));

    public static void main(String[] args) {
        executorService.execute( () ->{
            for (int i = 0; i < 10 ; i++) {
                Thread thread = new Thread("线程"+i){
                    @Override
                    public void run() {
                        for (int j = 0; j < 10 ; j++) {
                            System.out.println("--线程--" + Thread.currentThread().getName() + "，i的值为:" + j);
                        }
                        countDownLatch.countDown();
                    }
                };
                thread.start();
            }
        });
        System.out.println("收集数据线程结束");
        try {
            countDownLatch.await();
            System.out.println("压缩数据线程开始");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (countDownLatch.getCount() < 0){
            System.out.println("线程已经全部结束");
            executorService.shutdown();
        }

        System.out.println("线程池已经结束");





    }

}
